package reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 使用反射机制调用方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Person p = new Person();
        p.sayHello();

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入类的完全限定名:");
        String className = scan.nextLine();
        System.out.println("请输入方法名:");
        String methodName =scan.nextLine();

        //实例化类对象
        //Class cls = Class.forName("reflect.Person");
        Class cls = Class.forName(className);
        Object obj =cls.newInstance();

        //调用方法: 获取待调用方法的方法对象
        //Method method = cls.getMethod("sayHello");
        Method method =cls.getMethod(methodName);

        //通过方法对象来调用方法
        method.invoke(obj);
    }

















}
